package com.blb.search_service.listener;

import com.blb.search_service.entity.JsonResult;
import com.blb.search_service.entity.Spu;
import com.blb.search_service.feign.GoodsFeign;
import com.blb.search_service.repo.GoodsRepository;
import com.blb.search_service.repo.SpuRepository;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class GoodsRabbitListener {

    @Autowired
    private GoodsFeign goodsFeign;

    @Autowired
    private SpuRepository spuRepository;

    //配置监听器，bindings实现队列和交换机的绑定  @Queue配置队列 @Exchange配置交换机，key配置键
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue_save",durable = "true"),
            exchange = @Exchange(value = "blb.mall.exchange",
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC
            ),key={"goods.save"}))
    public void receiveSave(Long id){
        try {
            System.out.println("保存id:" + id);
            //通过feign调用Goods-service查询spu
            JsonResult<Spu> res = goodsFeign.findSpuById(id);
            Spu spu = res.getData();
            //保存到ES中
            spuRepository.save(spu);
            System.out.println("save同步完成");
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }

    //配置监听器，bindings实现队列和交换机的绑定  @Queue配置队列 @Exchange配置交换机，key配置键
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "queue_delete",durable = "true"),
            exchange = @Exchange(value = "blb.mall.exchange",
                    ignoreDeclarationExceptions = "true",
                    type = ExchangeTypes.TOPIC
            ),key={"goods.delete"}))
    public void receiveDelete(Long id){
        try {
            System.out.println("删除id:" + id);
            //从ES删除
            spuRepository.deleteById(id);
            System.out.println("delete同步完成");
        }catch (Exception ex){
            ex.printStackTrace();
        }
    }
}
